<route lang="json5">
{
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '活动详情',
  },
}
</route>

<template>
  <view style="position: relative;">
    <!-- 生成分享图 -->
    <view style="visibility: hidden;position: absolute;left: 0;top: 0;pointer-events: none;">
      <l-painter ref="painter" v-if="imgData.url">
        <l-painter-view css="display: inline-block; width: 750rpx;position: relative;">
          <l-painter-image
            :src="imgData.url"
            css="width: 750rpx; height: 600rpx; object-fit: cover; background: #f5f5f5" 
          />
          <l-painter-view
            css="background: rgba(0,0,0,0.5); width: 750rpx; position: absolute; left: 0; bottom: 0; padding: 12rpx; box-sizing: border-box;"
          >
            <l-painter-text 
              css="color: #fff; font-size: 32rpx;" 
              :text="imgData.text" 
            />
          </l-painter-view>
        </l-painter-view>
      </l-painter>
    </view>
    <!-- <view class="w-750rpx m-a font-size-0">
      <wd-img 
        width="100%" 
        height="750rpx" 
        mode="aspectFill"
        :src="activityDetail.fileInfoVo && activityDetail.fileInfoVo.preUrl" 
      />
    </view> -->

    <!-- 轮播图 -->
    <my-swiper :list="activityDetail.imagesList" imageMode="aspectFill" />

    <!-- 悬浮按钮列表 -->
    <view class="fixed right-32rpx top-816rpx w-80rpx h-80rpx flex-sb flex-col flex-wrap">
      <!-- 转发 -->
      <view class="btn-sd bg-linear-1 w-80rpx h-80rpx flex-center rounded-full color-white relative flex-wrap">
        <wd-button custom-class="share-btn" open-type="share">分享</wd-button>
        <view class="w-80rpx flex-center">
          <i class="iconfont icon-fenxiang font-size-36rpx"></i>
        </view>
        <text class="inline-block font-size-20rpx mt--16rpx">分享</text>
      </view>
    </view>

    <view class="w-750rpx m-a bg-white box-border pl-32rpx pr-32rpx"
      :class="[{ 'dark-color': themeConfig.theme === 'dark' }]"
    >
      <view class="font-size-40rpx leading-47rpx">
        <text class="font-bold">活动主题： </text>
        {{ activityDetail.title || '--' }}
        {{ activityDetail.feeType ? `, 费用${activityDetail.feeType}` : '' }}
      </view>
      <view class="mt-16rpx font-size-32rpx leading-33rpx color-#666">
        {{ formatDate(new Date(activityDetail.startTime), 'YYYY-MM-DD') }}
        ~
        {{ formatDate(new Date(activityDetail.endTime), 'YYYY-MM-DD') }}
      </view>
      <view class="mt-10rpx color-#666">
        <i class="iconfont icon-dingwei inline-block font-size-32rpx mr-6rpx"></i>
        <text class="font-size-32rpx" v-if="activityDetail.provinceName === activityDetail.cityName">
          {{ activityDetail.cityName || '-' }}{{ activityDetail.districtName || '-' }}
        </text>
        <text class="font-size-32rpx" v-else>
          {{ activityDetail.provinceName || '-' }}{{ activityDetail.cityName || '-' }}{{ activityDetail.districtName || '-' }}
        </text>
      </view>
      <view class="mt-16rpx font-size-32rpx leading-33rpx">
        <!-- {{ activityDetail.registrationCount ? `已有${activityDetail.registrationCount}` : '暂无' }}人报名 -->
        <text class="font-bold">计划人数: </text>
        <text class="color-#666">{{ activityDetail.participantsCount || 0 }}人</text>
      </view>
      <view class="mt-16rpx font-size-32rpx leading-40rpx pb-32rpx">
        <text class="font-bold">注意事项: </text>
        <view class="color-#666">
          <rich-text :nodes="activityDetail.remarks || ''"></rich-text>
        </view>
      </view>
    </view>
    <view class="border-1px"></view>

    <view class="w-center">
      <view class="mt-16rpx font-size-32rpx leading-40rpx pb-16rpx">
        <text class="font-bold">活动详情: </text>
      </view>
      <rich-text :nodes="activityDetail.description || ''"></rich-text>
    </view>
    
    <view class="border-1px mt-64rpx"></view>
    <view class="w-750rpx m-a" v-if="eventRegistrationInfoVos.length">
      <view class="w-center py-20rpx font-900">
        参与嘉宾
      </view>
      
      <!-- 没有数据 -->
      <view v-if="!eventRegistrationInfoVos.length" class="color-#999 font-size-26rpx py-48rpx text-center">
        暂无参与嘉宾
      </view>

      <template v-for="item in eventRegistrationInfoVos">
        <view class="w-center flex-sb-center py-24rpx">
          <base-img-box :size="96" :round="96" :imgSrc="getInfo(item).preUrl" :thumbnailPreUrl="getInfo(item).thumbnailPreUrl" />
          <view class="pl-24rpx" style="flex: 1;">
            <view class="flex-sb-center">
              <view class="font-size-32rpx font-900 max-w-200rpx ellipsis" @click="toUserDetail(getInfo(item).userId)">
                {{ getInfo(item).nickname }}
              </view>
              <view class="font-size-24rpx color-#666 max-w-300rpx ellipsis">
                {{ `${getInfo(item).gender == '0' ? '男' : '女'}` }}·{{ calculateAge(getInfo(item).birthYearMonth) }}岁·{{ getInfo(item).professionName }}
              </view>
            </view>
            <view class="flex-sb-center font-size-24rpx">
              <view class="color-#666">ID: {{ getInfo(item).code }}</view>
              <view class="color-#666 max-w-400rpx ellipsis">{{ getInfo(item).areaName }}</view>
            </view>
          </view>
        </view>
        <view class="border-1px"></view>
      </template>
    </view>
    <!-- <view class="w-center font-size-32rpx !mt-32rpx pb-186rpx color-#666">
      {{ activityDetail.description || '--' }}
    </view> -->

    <!-- 报名活动按钮 -->
    <view class="btn-full w-center position-b-center !fixed !bottom-24rpx"
      :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }"
      v-if="!activityDetail.registered && activityDetail.canRegistrateFlag"
    >
      <wd-button 
        class="btn-w-full btn-h-78"
        :loading="registerLoading"
        @click="submit"
      >报名活动</wd-button>
    </view>

    <!-- 底部占位 -->
    <view class="w-full h-134rpx"
      :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }"
    ></view>
    
    <wd-action-sheet 
      v-model="showPaySheet" 
      :actions="getActions" 
      cancel-text="取消"
      :title="`报名活动需支付${activityDetail.feeAmount}乐缘币`"
      @select="selectPayMethod"
    />
  </view>
</template>
  
<script lang="ts" setup>
import LPainter from "@/components/lime-painter/components/l-painter/l-painter.vue";
import LPainterView from "@/components/lime-painter/components/l-painter-view/l-painter-view.vue";
import LPainterImage from "@/components/lime-painter/components/l-painter-image/l-painter-image.vue";
import LPainterText from "@/components/lime-painter/components/l-painter-text/l-painter-text.vue";
import MySwiper from "@/components/swiper/my-swiper.vue";
import baseImgBox from "@/components/base/base-img-box.vue";
import { EventRegistrationInfo, EventRegistrationInfoEventWechat, GetEventInfo, GetEventRegistrationInfo } from "@/service/db_activity";
import { useCommonStore, useThemeStore, useUserStore } from "@/store";
import { Activity } from '@/service/types/activity';
import { useMessage, useToast } from 'wot-design-uni'
import { calculateAge, comUploadFile, formatDate, getActions } from "@/utils";
import { share } from "@/enum/index";

const toast = useToast();
// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync();
// 主题颜色
const { themeConfig } = useThemeStore();
const common = useCommonStore();
const user = useUserStore();
const message = useMessage();

const activityId = ref('');
const loading = ref<boolean>(false);
const activityDetail = ref({} as Activity.ActivityDetail);

/**
 * 获取活动详情
 */
const getEventInfo = async () => {
  try {
    loading.value = true;
    const { data } = await GetEventInfo({ id: activityId.value });
    loading.value = false;
    activityDetail.value = data;
    !imgData.value.url && getImgData();
  } catch (error) {
    loading.value = false;
    console.log('error', error)
  }
}

// 参与人列表
const eventRegistrationInfoVos = computed(() => {
  return activityDetail.value.eventRegistrationInfoVos || [];
})

// 跳转用户详情
const toUserDetail = (id: any) => {
  if (!user.isLogined) {
    uni.navigateTo({ url: '/pages/login/index' });
    return
  }
  uni.navigateTo({ 
    url: `/activity/userDetail?id=${id}`
  })
}

const getInfo = computed(() => {
  return (item) => {
    const userProfileInfoVo = item.userProfileInfoVo || {};
    const userInfoVo = item.userInfoVo || {};
    const personAvatar = userInfoVo.personAvatar || {};
    const { provinceName, cityName, districtName } = userProfileInfoVo;
    let areaList = [provinceName, cityName, districtName];
    if (provinceName && provinceName === cityName) {
      areaList = [cityName, districtName];
    }
    return {
      ...userProfileInfoVo,
      preUrl: personAvatar.preUrl,
      code: userInfoVo.code,
      areaName: areaList.join('·'),
      userId: item.userId,
      thumbnailPreUrl: personAvatar.thumbnailPreUrl,
    }
  }
})

/** 获取活动报名表详情 */
const getEventRegistrationInfo = async () => {
  try {
    const { data } = await GetEventRegistrationInfo({ id: activityId.value });
  } catch (error) {
    console.log('error', error)
  }
}

/**
 * 报名活动请求状态
 */
const registerLoading = ref<boolean>(false);
/**
 * 报名活动
 */
const register = async () => {
  try {
    registerLoading.value = true;
    const res = await EventRegistrationInfo({
      userId: user.userInfo.id,
      eventId: activityId.value,
      paymentAmount: activityDetail.value.feeAmount
    });
    registerLoading.value = false;
    if (res.code == '6000012') {
      // common.paymentMsgConfirm({
      //   userId: user.userInfo.id,
      //   type: 'join_event',
      //   relatedBusinessId: activityId.value,
      //   amount: activityDetail.value.feeAmount || 0
      // }, () => {
      //   // 充值成功
      //   toast.show(res.message);
      // }, false, message)
      return 
    }
    getEventInfo();
    toast.show({ msg: '报名成功', duration: 3000 });
  } catch (error) {
    registerLoading.value = false;
    console.log('error', error)
  }
}

// 显示支付方式
const showPaySheet = ref(false);

const submit = () => {
  if (!user.getUseVo.userProfileInfoVo.nickname) {
    setTimeout(() => {
      uni.navigateTo({ url: '/activity/info' });
    }, 1000)
    toast.show({ msg: '请先完善个人资料', duration: 3000 });
    return;
  }
  if (!user.activityInfo.id) {
    toast.show('请先填写资料');
    setTimeout(() => {
      uni.navigateTo({ url: '/activity/addActivityInfo' })
    }, 1000)
    return
  }
  // 免费
  if (activityDetail.value.feeAmount === 0) {
    register();
    return;
  }
  showPaySheet.value = true;
  // message
  //   .confirm({
  //     msg: `将会消耗${activityDetail.value.feeAmount || 0}的乐缘币, 是否报名？`,
  //     title: '报名提示'
  //   })
  //   .then(() => {
  //     register();
  //   })
  //   .catch(() => {
  //     console.log('点击了取消按钮')
  //   })
}

// 选择支付方式
const selectPayMethod = (options) => {
  const { item } = options || {};
  if (item.type === 'wechat') {
    common.paymentMsgConfirm({
      userId: user.userInfo.id,
      eventId: activityId.value,
      paymentAmount: activityDetail.value.feeAmount

      // userId: user.userInfo.id,
      // type: 'join_event',
      // relatedBusinessId: activityId.value,
      // amount: activityDetail.value.feeAmount || 0
    }, () => {
      getEventInfo();
      // 充值成功
      toast.show({ msg: '报名成功', duration: 3000 });
    }, false, message, true, EventRegistrationInfoEventWechat)
  } else {
    register();
  }
}

// base64转换临时路径
function base64ToTempPath(base64Data) {
  const fs = uni.getFileSystemManager()
  const tempFilePath = `${wx.env.USER_DATA_PATH}/temp_${Date.now()}.jpg`
  fs.writeFileSync(tempFilePath, base64Data, 'base64')
  return tempFilePath
}

const imgData = ref<any>({});
const painter = ref();
const shareUrl = ref('');
const getImgData = () => {
  const { 
    title, 
    startTime,
    endTime,
    imagesList,
    provinceName,
    cityName,
    districtName,
  } = activityDetail.value || {};

  const _startTime = formatDate(new Date(startTime), 'YYYY-MM-DD');
  const _endTime = formatDate(new Date(endTime), 'YYYY-MM-DD');
  const firstItem: any = imagesList ? imagesList[0] : {};
  if (!firstItem.thumbnailPreUrl) return;
  
  const area = [provinceName, cityName, districtName].filter((value, index, self) => {
    return self.indexOf(value) === index;
  }).join('');
  
  imgData.value = {
    url: firstItem.thumbnailPreUrl || '',
    text: `活动主题：${title}\n活动时间：${_startTime}~${_endTime}\n活动区域：${area}`,
    res: '',
  }

  setTimeout(() => {
    painter.value.canvasToTempFilePathSync({
      fileType: 'jpg',
      quality: 0.2,
      success: async (res) => {
        try {
          let tempPath = res.tempFilePath;
          // #ifdef MP-WEIXIN
          const pureBase64 = res.tempFilePath.replace(/^data:image\/\w+;base64,/, '');
          tempPath = base64ToTempPath(pureBase64);
          // #endif

          // 上传图片
          const _res = await comUploadFile({
            url: '/file-info',
            tempFilePath: tempPath,
            formData: {}
          })
          if (_res.code != 200) {
            return toast.show(res.message);
          }
          shareUrl.value = _res.data.preUrl;
        } catch (error) {
          console.log('err => comUploadFile', error);
        }
      },
      fail(e) {
        console.log('err', e);
      }
    })
  }, 500)
}

onLoad((options) => {
  const { id } = options || {};
  activityId.value = id;
  getEventInfo();
})

onShow(() => {
  nextTick(() => {
    // 设置页面标题
    themeConfig.title = '活动详情';
  })
})

onShareAppMessage(() => {
  const id = user.userInfo.id || '';
  const list = activityDetail.value.imagesList || [];
  const first = list[0] || {};
  // first.preUrl || 
  return {
    title: '“告别单身”官方主题活动，\n         ————期待您的到来！',
    path: `/activity/activityDetail?id=${activityId.value || ''}` + '&instrId=' + id,
    imageUrl: shareUrl.value || share
  }
})
</script>

<style lang="scss">
img {
  max-width: 750rpx;
}
// 轮播图高度
:deep(.wd-swiper__track) {
  height: 637rpx !important;
}
</style>
  